package com.postsuperman.proxypool.common;

import com.postsuperman.proxypool.pojo.HttpProxy;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author ： Lwl postserupman
 * @Description TODO
 * @Date 2019/2/27 12:06
 * @Version 1.0
 */
public class ProxyPool {

    public static CopyOnWriteArrayList<HttpProxy> proxyList = new CopyOnWriteArrayList<>();
    public static Map<String, Class> proxyMap = new HashMap<>();
    private static AtomicInteger index = new AtomicInteger();

    /**
     * 采用round robin算法来获取Proxy
     *
     * @return
     */
    public static HttpProxy getProxy() {

        HttpProxy result = null;

        if (proxyList.size() > 0) {
            index.incrementAndGet();
            if (index.get() > proxyList.size() - 1) {
                index.set(0);
            }

            result = proxyList.get(index.get());
        }

        return result;
    }

    public static void add(HttpProxy proxy) {

        if (proxy != null) {
            proxyList.add(proxy);
        }
    }

    public static void add(List<HttpProxy> proxies) {

        if (proxies != null && proxies.size() > 0) {
            proxyList.addAll(proxies);
        }
    }

}
